import {
  ADD_TODO,
  TOGGLE_TODO,
  REMOVE_TODO
} from './actionType';
import initialState from './state';
import action from './action';
import {
  useReducer
} from 'react';

function reducer(state, {
  type,
  payload
}) {
  const {
    onAddTodo,
    onToggleTodo,
    onRemoveTodo
  } = action(state);

  switch (type) {
    case ADD_TODO:
      return onAddTodo(payload);
      break;
    case TOGGLE_TODO:
      return onToggleTodo(payload);
    case REMOVE_TODO:
      return onRemoveTodo(payload);
    default:
      break;
  }
}

export default function () {
  /**
   * const [state, todoDispatch] = useReducer(reducer, initialState);
   * todoDispatch名称是自定义的, 它可以操作和更改数据
   * 使用方法：
   * todoDispatch({
   *   type,
   *   payload
   * })
   */
  return useReducer(reducer, initialState);
}